﻿using ProTrack.Entity;
using ProTrack.IRepository;
using ProTrack.IServices.Plans;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace ProTrack.Services.Plans
{
    public class PlanCalendarServices : IPlanCalendarServices
    {
        //异步方法
        public PlanCalendarServices(IBaseRepository db)
        {
            Db = db;
        }

        public IBaseRepository Db { get; }

        public async Task<IEnumerable<PlanTeam>> GetCurrentPlanAsync(int PageIndex, int PageSize, string Date, string ShiftWay, string TeamName)
        {
            
            string sql = "select * from PlanTeam  where CONVERT(date, StartDate)<= @Dates   and  CONVERT(date, EndDate)>= @Dates ";

            if (!string.IsNullOrEmpty(TeamName))
            {
                sql += " and TeamName  like @TeamName ";
            }
            if (!string.IsNullOrEmpty(ShiftWay) && !ShiftWay.Equals("全部"))
            {
                sql += " and ShiftWay  = @ShiftWay ";
            }

            sql += " order by StartDate desc offset @PageSize*(@PageIndex-1) row fetch next @PageSize rows only ";


            var list = await Db.QueryAsync<PlanTeam>(sql,new {
                Dates = DateTime.Parse(Date).ToString("yyyy-MM-dd"),
                ShiftWay,
                TeamName="%"+ TeamName+"%",
                PageIndex,PageSize
            });
            return list;
        }


        public async Task<int> GetCurrentPlanCountAsync(string Date, string ShiftWay, string TeamName)
        {

            string sql = "select count(*) from PlanTeam  where CONVERT(date, StartDate)<= @Dates   and  CONVERT(date, EndDate)>= @Dates ";

            if (!string.IsNullOrEmpty(TeamName))
            {
                sql += " and TeamName  like @TeamName ";
            }
            if (!string.IsNullOrEmpty(ShiftWay) && !ShiftWay.Equals("全部"))
            {
                sql += " and ShiftWay  = @ShiftWay ";
            }

            var count = await Db.GetRecoreCountAsync(sql, new
            {
                Dates = DateTime.Parse(Date).ToString("yyyy-MM-dd"),
                ShiftWay,
                TeamName = "%" + TeamName + "%",
            });
            return count;
        }

        public async Task<IEnumerable<PlanTeam>> GetPlanAsync(string Date)
        {
            string sql = "select * from PlanTeam  where  DateDiff(MONTH,StartDate,@Month) = 0 or DateDiff(MONTH,StartDate,@NextMonth) = 0";


            //默认查询这个月和下个月的排班数据
            var dates = DateTime.Parse(Date+ $"-{DateTime.Now.Day}").AddMonths(1).ToString("yyyy-MM-dd");
            var list = await Db.QueryAsync<PlanTeam>(sql,new { Month =$"{Date}-{DateTime.Now.Day}", NextMonth = dates });
            return list;

        }
    }
}
